<?php

abstract class DatabaseTablePage extends Page
{
    const CREATE_ACTION = "create";
    const DELETE_ACTION = "delete";
    const UPDATE_ACTION = "update";
    const ITEMS_VAR_NAME = 'ITEMS';

    /**
     * @var InventoryManager
     */
    protected $itemManager;

    /**
     * @var InventoryForm
     */
    protected $form;

    public function Process()
    {
        if (Request::IsAjaxRequest())
        {
            $this->HandleAjaxRequest();
            die();
        }
        $this->SetVar('INVENTORY_TABLE', $this->GetInventoryTableHtml());
    }

    public function Init()
    {
        $this->SetItemManager();
        $this->SetInventoryForm();
    }

    protected abstract function SetItemManager();

    protected abstract function SetInventoryForm();

    protected abstract function GetTableTemplate();

    protected function GetInventoryTableHtml()
    {
        $items = $this->itemManager->SelectAll();
        $itemsCount = $this->itemManager->GetSelectCount();
        $this->SetVar("ITEMS_COUNT", $itemsCount);
        return TemplateEngine::getView($this->GetTableTemplate(), array(self::ITEMS_VAR_NAME => $items));
    }

    private function HandleAjaxRequest()
    {
        $action = Request::Post('action');
        $error = "";
        if (($action == self::CREATE_ACTION) || ($action == self::UPDATE_ACTION))
        {
            $this->form->Bind();
            if ($this->form->IsValid())
            {
                $this->form->Save();
            }
        }
        else if ($action == self::DELETE_ACTION)
        {
            $itemId = Request::Post('id');
            try
            {
                $this->itemManager->Delete($itemId);
            }
            catch (Exception $exception)
            {
                $error = "Не удалось удалить запись из базы данных.\n Она находится в списке записей об аренде";
            }
        }

        $content = (empty($error)) ? $this->GetInventoryTableHtml() : "";
        $response = array(
            'error' => $error,
            'content' => $content
        );
        echo json_encode($response);
    }
}